;(function () {
'use strict';
/* 黄鑫 2014-12-19 */

angular.module('sasApp')
  .factory('RoleConstructor', RoleConstructorFactory);

  /*
   * @ngdoc service
   * @name roleTreeCore
   * @module sysMng.common
   * @description
   *
   * 该模块为公用核心模块，包含了一些核心算法函数，treeBuild、serialize
   *w
   * @returns coreService.$service
   */

function RoleConstructorFactory(){

  var roleConstructorService = {
    treeBuild: treeBuild,
    serialize: serialization
  };
  
  return roleConstructorService;
  
  /*
   * @name treeBuild
   *
   * @param {array} dataArr 对象数组，每个对象都应该包含 parentRole 以判断父对象
   *
   * @returns {object} 构建完成的嵌套对象
   */
  function treeBuild(dataArr,roleId){
    var delIndex;
    var roleTree = {};

    angular.forEach(dataArr,function(item,index){
      if(roleId === item.roleId ){
        roleTree = {
          roleId: item.roleId,
          roleName: item.roleName,
          childRoles: []
        };
        delIndex = index;
      }
    });
    buildChild(roleTree,dataArr, 0);

    return roleTree;

    /*
     * @param {object} parent 父对象
     * @param {array} dataArr 对象数组
     * @param {number} level 当前遍历层级，初始时为0
     */
    function buildChild(parent,dataArr,level){
      if(parent.childRoles === undefined){
        parent.childRoles = [];
      }
      angular.forEach(dataArr, function(item){
        if(item.parentRole === parent.roleId){
          for(var i = 0, lvl = level + 1; i < lvl; i++){
            item.roleName = '--' + item.roleName;
          }
          buildChild(item,dataArr, level+1);
          parent.childRoles.push(item);
        }
      });
    }
  }

  /*
   * @name serialization
   *
   * @param {object} treeObj 嵌套了子集的对象
   *
   * @returns {array} 返回按照前序遍历树型数据的数组 
   *
   */
  function serialization(treeObj){
    var series = [];
    treeSerialization(treeObj, series);
    return series;

    /*
     * @param {object} treeObj 包含嵌套关系的源对象 
     * @param {array} series 待push的空数组，由serialization构建
     */
    function treeSerialization(treeObj,series){
      if(!treeObj.parentRole){
        series.push({roleId: treeObj.roleId, roleName: treeObj.roleName});
      }
  
      if(angular.isArray(treeObj.childRoles) && treeObj.childRoles === []){
        return;
      }
      angular.forEach(treeObj.childRoles, function(item){
        series.push({roleId: item.roleId, roleName: item.roleName });
        treeSerialization(item,series);
      });
    }
  }
}
})();